package server;

import global.ShareContext;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.http.HttpRequestDecoder;
import org.jboss.netty.handler.codec.http.HttpResponseEncoder;

import srmi.NativeInvoker;

public class NettyServer {

	private ServerHandler handler;
	private NativeInvoker invoker;
	
	private String host;
	private int port;

	public NettyServer(ShareContext context, String host, int port) {
		this.host = host;
		this.port = port;
		invoker = new NativeInvoker(context);
		handler = new ServerHandler(invoker);
	}
	
	public NativeInvoker getInvoker(){
		return invoker;
	}
	public ServerHandler getHandler(){
		return handler;
	}

	public void startUp() {
		ServerBootstrap bootStrap = new ServerBootstrap(
				new NioServerSocketChannelFactory(
						Executors.newCachedThreadPool(),
						Executors.newCachedThreadPool()));
		bootStrap.setPipelineFactory(new HttpServerPipelineFactory(handler));
		bootStrap.bind(new InetSocketAddress(host,port));
	}

	private static class HttpServerPipelineFactory implements
			ChannelPipelineFactory {
		private ServerHandler handler = null;

		public HttpServerPipelineFactory(ServerHandler handler) {
			this.handler = handler;
		}

		@Override
		public ChannelPipeline getPipeline() throws Exception {
			ChannelPipeline pipeline = Channels.pipeline();
			pipeline.addLast("decoder", new HttpRequestDecoder());
			pipeline.addLast("encoder", new HttpResponseEncoder());
			pipeline.addLast("handler", handler);
			return pipeline;
		}
	}
}
